<template>
    <div class="reset_container">
        <span class="reset_title">重置用户密码</span>

        <el-steps :active="resetStep" align-center class="reset_step">
            <el-step title="第一步" description="验证账号与邮箱" />
            <el-step title="第二步" description="获取邮箱验证码" />
            <el-step title="第三步" description="重置登录密码" />
        </el-steps>

        <el-form>
            <template v-if="resetStep === 1">
                <el-form-item label="注册账号" class="input">
                    <el-input v-model.lazy="registerAccount" 
                        placeholder="请输入您注册时所使用的账号"/>
                </el-form-item>
                <el-form-item label="注册邮箱" v-if="resetStep === 1" class="input">
                    <el-input v-model.lazy="registerEmail" 
                        placeholder="请输入您注册时所使用的邮箱地址"
                        @blur="handleEmailBlur"/>
                    <span :class="emailTipsClass">输入内容不符合电子邮件地址规范</span>
                </el-form-item>
            </template>

            <el-form-item label="验证码" class="input" v-else-if="resetStep === 2">
                <el-input v-model="validationCode"
                            placeholder="请输入您接收到的4位验证码"
                            @blur="handleValidationCodeBlur">
                    <template #append>
                        <span @click="reRequestValidateCode" class="count_down">{{ countDown }}</span>
                    </template>
                </el-input>
            </el-form-item>
     
            <template v-else>
                <el-form-item label="重置密码" class="input">
                    <el-input v-model="resetPassword" 
                              @blur="handleResetPasswordBlur"/>
                </el-form-item>
                <el-form-item label="确认密码" class="input">
                    <el-input v-model="confirmPassword"
                              type = "password"
                              show-password
                              @blur="handleConfirmPasswordBlur"/>
                </el-form-item>
            </template>
        </el-form>
        <el-button @click = "handleNextStep"
            v-loading="isNextStepLoading" 
            :disabled="!nextStepEnable">{{ nextStepText }}</el-button>
    </div>
</template>

<script setup lang="ts" name="ResetPassword">
    import { reactive, ref, watch } from 'vue'
    import { validateEmailReq } from "@/requests/request";
    import { ElMessage } from 'element-plus';
    import router from '@/router';
    let registerAccount = ref("")
    let registerEmail = ref("")
    let emailTipsClass = reactive({
        show_email_tips: false,
        hide_email_tips: true,
    })

    let validationCode = ref("")
    let countDown = ref("获取验证码")
    let secondsRemain = 60
    let startCountDown = ref(false)

    let nextStepEnable = ref(false)

    let resetPassword = ref("")
    let confirmPassword = ref("")

    let resetStep = ref(1)
    let isNextStepLoading = ref(false)
    let nextStepText = ref("下一步")

    
    // 邮箱格式的本地基本验证
    function handleEmailBlur() {
        const emailReg = /^\w{3,}(\.\w+)*@[A-z0-9]+(\.[A-z]{2,5}){1,2}$/
        if (emailReg.test(registerEmail.value)) {
            emailTipsClass.hide_email_tips = true
            emailTipsClass.show_email_tips = false
            nextStepEnable.value = true
        } else {
            emailTipsClass.hide_email_tips = false
            emailTipsClass.show_email_tips = true
        } 
    }

    // 验证码格式的本地基本验证
    function handleValidationCodeBlur() {
        const validationCodeReg = /\d{4}$/
        if (validationCodeReg.test(validationCode.value)) {
            nextStepEnable.value = true
        } else {
            nextStepEnable.value = false
        }
    }


    //
    function handleResetPasswordBlur() {
        if (resetPassword.value.length <= 0) {
            ElMessage( {
                message: "重置密码不能为空",
                type: "error"
            })
            return
        }
        if (confirmPassword.value.length > 0) {
            if (resetPassword.value !== confirmPassword.value) {
                ElMessage( {
                    message: "两次输入的密码不一致",
                    type: "error"
                })
                return
            }
        }
        if (resetPassword.value === confirmPassword.value) {
            nextStepEnable.value = true
        }
    }

    function handleConfirmPasswordBlur() {
        if (confirmPassword.value.length <= 0) {
            ElMessage( {
                message: "确认密码不能为空",
                type: "error"
            })
            return
        }
        if (resetPassword.value.length > 0) {
            if (resetPassword.value !== confirmPassword.value) {
                ElMessage( {
                    message: "两次输入的密码不一致",
                    type: "error"
                })
                return
            }
        }
        if (resetPassword.value === confirmPassword.value) {
            nextStepEnable.value = true
        }
    }



    // 验证邮箱后，返回4位数字的验证码
    async function requestValidateCode(): Promise<any> {
        const params = {
            account: registerAccount.value,
            email: registerEmail.value
        }
        try {
            const data = await validateEmailReq.get('./validateEmail', {params, timeout: 20_000}) 
            return Promise.resolve(data) 
        } catch(error: any) {
             return Promise.reject(error)
        }
    }

    // 获取验证码
    async function getValidationCode(): Promise<any> {
        const params = {
            account: registerAccount.value,
        }
        try {
            const data = await validateEmailReq.get('./validationCode', {params, timeout: 20_000}) 
            return Promise.resolve(data) 
        } catch(error: any) {
             return Promise.reject(error)
        }
    }

    // 重置密码
    async function requestResetPassword(): Promise<any> {
        const fd = new FormData()
        fd.append("account", registerAccount.value)
        fd.append("resetPassword", resetPassword.value)
        const headers = {
            ContentType: "application/x-www-form-urlencoded",
        }
        try {
            const data = await validateEmailReq.post('./resetPassword', fd, {headers}) 
            return Promise.resolve(data) 
        } catch(error: any) {
                return Promise.reject(error)
        }
    }

    function handleNextStep() {
        switch(resetStep.value) {
            case 1: {
                isNextStepLoading.value = true
                requestValidateCode().then((res: any)=>{
                        const {resCode, message} = res.data
                        if (resCode === 0) {
                            ElMessage({
                                message: message,
                                type: 'success',
                            })
                            nextStepEnable.value = false
                            resetStep.value = resetStep.value + 1
                            startCountDown.value = true
                        } else {
                            ElMessage({
                                message: message,
                                type: 'error',
                            })
                        }
                        isNextStepLoading.value = false
                    })
                    .catch((reason: any)=> {
                        ElMessage({
                                message: reason,
                                type: 'error',
                        })
                        isNextStepLoading.value = false
                    })
                }
                break;
            case 2:
                isNextStepLoading.value = true
                getValidationCode().then((res: any)=>{
                    const {data} = res.data
                    if (validationCode.value === data) {
                        nextStepEnable.value = false
                        resetStep.value = resetStep.value + 1
                        nextStepText.value = "重置"
                    } else {
                        ElMessage({
                            message: "验证码错误",
                            type: 'error',
                        })
                    }
                    isNextStepLoading.value = false
                }).catch((reason: any)=> {
                    ElMessage({
                        message: reason,
                        type: 'error',
                    })
                    isNextStepLoading.value = false
                })
                break;
            case 3:
                isNextStepLoading.value = true
                requestResetPassword().then((res:any) => {
                    const {data, message} = res.data
                    ElMessage( {
                        message,
                        type: data ? "success": "error"
                    })
                    if (data) {
                        router.push( {
                            name: "Login"
                        })
                    }
                }).catch((reason: any)=>{
                    ElMessage( {
                        message: reason,
                        type: "error"
                    })
                })
                break;
            default:
                break;
        }
    }


    function reRequestValidateCode() {
        console.log("reRequestValidateCode(), return");
        if (secondsRemain < 60) {
            console.log("reRequestValidateCode(), return");
            return 
        }
        requestValidateCode().then((res: any)=>{
                const {resCode, message} = res.data
                if (resCode === 0) {
                    ElMessage({
                        message: message,
                        type: 'success',
                    })
                    startCountDown.value = true
                } else {
                    ElMessage({
                        message: message,
                        type: 'error',
                    })
                }
            })
            .catch((reason: any)=> {
                ElMessage({
                        message: reason,
                        type: 'error',
                })
            })
    }


    // 倒计时
    let timerId: any = undefined
    function clearTimer() {
        if (timerId) {
            clearInterval(timerId)
            timerId = undefined
            startCountDown.value = false
        }
    }
    watch(startCountDown, (newVal)=> {
        if (newVal) {
            clearTimer()
            timerId = setInterval(()=> {
                if (secondsRemain <= 0) {
                    countDown.value = "获取验证码" 
                    secondsRemain = 60
                    clearTimer()
                    return
                }
                countDown.value = secondsRemain-- + "s"
            }, 1000)
        } else  {
            clearTimer()
        }
    })
</script>

<style scoped lang="scss">
    .reset_container {
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-top: 60px;
        --el-color-primary: purple;
        .reset_title {
            font-size: 24px;
            margin-top: 20px;
            margin-bottom: 20px;
        }
        .reset_step {
            margin-top: 20px;
            margin-bottom: 50px;
            width: 60%;
        }
        .show_email_tips {
            color: red;
            visibility: visible;
        }
        .hide_email_tips {
            visibility: hidden;
        }
        .input {
            width: 480px;
        }
        .count_down {
            cursor: pointer;
        }
    }
</style>